package http

import (
	"encoding/gob"
	"gitee.com/legend9999/publisher/modle"
	"html/template"
	"time"
)

func init() {
	gob.Register(new(modle.User))

}

func initTemplateFunc() template.FuncMap {
	funcMap := template.FuncMap{
		"date": formatDate,
		"short": func(s string, l int) string {
			r := []rune(s)
			if len(r) < l+3 {
				return s
			}
			return string(r[:l]) + "..."
		},
		"bookStage": func(status modle.Status) string {
			return ""
		},
		"nextStatus": nextStatus,
		"nextStatusName": func(status modle.Status) string {
			nextStatus := nextStatus(status)
			return bookStatusName(nextStatus)
		},
		"bookStatusName":   bookStatusName,
		"statusStartDate":  statusStartDate,
		"statusFinishDate": statusFinishDate,
		"statusUser":       statusUser,
		"statusIsFinish":   statusIsFinish,
		"statusIsStart":    statusIsStart,
	}
	return funcMap
}

func nextStatus(status modle.Status) (nextStage modle.Status) {
	var nexStatus modle.Status
	if status == modle.S1_7 {
		nexStatus = modle.NO
	} else if status == modle.S2_3 {
		nexStatus = modle.NO
	} else if status == modle.S3_3 {
		nexStatus = modle.NO
	} else {
		nexStatus = status + 1
	}
	return nexStatus
}

func bookStatusName(status modle.Status) string {
	switch status {
	case modle.S1_1:
		return "原稿"
	case modle.S1_2:
		return "一校"
	case modle.S1_3:
		return "二校"
	case modle.S1_4:
		return "三校"
	case modle.S1_5:
		return "核红"
	case modle.S1_6:
		return "最终"
	case modle.S1_7:
		return "出书"
	case modle.S2_1:
		return "已开发排单"
	case modle.S2_2:
		return "平台已有信息"
	case modle.S2_3:
		return "已填报"
	case modle.S3_1:
		return "已汇总"
	case modle.S3_2:
		return "已开销货清单"
	case modle.S3_3:
		return "已结账"
	case modle.S4_1:
		return "结账完成"
	}
	return "未知"
}
func formatDate(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

func statusStartDate(book modle.Book, status modle.Status) string {
	for _, bookStatus := range book.Statuses {
		if bookStatus.Status == status {
			if bookStatus.StartTime == nil {
				return ""
			}
			return formatDate(*bookStatus.StartTime)
		}
	}
	return ""
}

func statusIsFinish(book modle.Book) bool {
	for _, bookStatus := range book.Statuses {
		if bookStatus.Status == book.Status {
			if bookStatus.FinishTime == nil {
				return false
			}
			return true
		}
	}
	return false
}
func statusIsStart(book modle.Book) bool {
	for _, bookStatus := range book.Statuses {
		if bookStatus.Status == book.Status {
			if bookStatus.StartTime == nil {
				return false
			}
			return true
		}
	}
	return false
}
func statusFinishDate(book modle.Book, status modle.Status) string {
	for _, bookStatus := range book.Statuses {
		if bookStatus.Status == status {
			if bookStatus.FinishTime == nil {
				return ""
			}
			return formatDate(*bookStatus.FinishTime)
		}
	}
	return ""
}
func statusUser(book modle.Book, status modle.Status) string {
	for _, bookStatus := range book.Statuses {
		if bookStatus.Status == status {
			return bookStatus.User.Name
		}
	}
	return "无"
}
